package com.xtsoft.platform.task.controller;


import com.fasterxml.jackson.databind.JsonMappingException;
import com.xtsoft.core.controller.GenericController;
import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;

import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.globe.utils.SecurityUtils;

import com.xtsoft.platform.task.domain.SchedulerTask;
import com.xtsoft.platform.task.service.SchedulerTaskService;
import com.xtsoft.platform.task.service.TaskManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;

import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.getUser;

/**
 * 
 * @ClassName: SchedulerTask
 *             <p>
 *             调度任务处理类
 *             </p>
 * @author: Codegen-代码生成器
 * @date: 2019年12月3日 上午10:59:46
 */
@Tag(name = "调度任务--处理接口" )
@RestController
public class SchedulerTaskController extends GenericController {

	private final Logger log = LoggerFactory.getLogger(SchedulerTaskController.class);

	@Autowired
	private SchedulerTaskService schedulerTaskService;
	
	@Autowired
	private TaskManager taskManager;

	/**
	 * <p>
	 * 新增一个调度任务
	 * </p>
	 * 
	 * @param schedulerTask 要新增的调度任务
	 * @return ResponseEntity<ResultMsg>, ResultMsg的Data中包含 调度任务
	 * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@PostMapping("/schedulerTask/add")
	@Parameter(name = "SchedulerTask", description = "调度任务", required = false)
	@Operation(summary ="新增，根据前台传递的任务新增")
	public ResponseEntity<ResultMsg> add(
			@RequestBody SchedulerTask schedulerTask)
			throws URISyntaxException {
		if (null == schedulerTask) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "新增调度任务失败，传递的调度任务为空"), HttpStatus.OK);
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("新增调度任务开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		if (!StringUtils.isEmpty(schedulerTask.getSchedulerTaskId())) {
			log.info("新增调度任务失败，新调度任务不能具有SchedulerTaskId属性值", user.getLoginId(),
					user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "新增调度任务失败，新调度任务不能具有SchedulerTaskId属性值"),
					HttpStatus.OK);
		}

		SchedulerTask result = schedulerTaskService.save(schedulerTask);
		log.info("新增调度任务成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "新增成功", result), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 更新一个调度任务
	 * </p>
	 * 
	 * @param schedulerTask 要更新的调度任务
	 * @return ResponseEntity<ResultMsg>, json格式
	 * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@PostMapping("/schedulerTask/update")
	@Parameter(name = "SchedulerTask", description = "调度任务", required = false)
	@Operation(summary ="更新，根据传递的 调度任务更新实体")
	public ResponseEntity<ResultMsg> update(
		  @RequestBody SchedulerTask schedulerTask)
			throws URISyntaxException {
		if (null == schedulerTask) {

			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新调度任务失败，传递的调度任务为空"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("单条更新调度任务开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		// 若 调度任务无主键值，说明调用错误
		if (StringUtils.isBlank(schedulerTask.getSchedulerTaskId())) {
			log.info("单条更新调度任务失败，调度任务对象SchedulerTaskId无属性值", user.getLoginId(),
					user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新失败，调度任务对象SchedulerTaskId无属性值"), HttpStatus.OK);
		}

		SchedulerTask result = schedulerTaskService.save(schedulerTask);
		log.info("单条更新调度任务成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "更新成功", result), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 查询调度任务列表
	 * </p>
	 * 
//	 * @param pageable,页码信息
	 * @return ResponseEntity<QueryResult<SchedulerTask>>，json格式
	 * @throws URISyntaxException 如果出错，则产生页码信息的 HTTP headers
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@GetMapping("/schedulerTask/getAll")
	@Operation(summary ="查询，根据传递的条件查询调度任务列表，条件参数在Request中")
	public ResponseEntity<ResultMsg> getAll()
			throws URISyntaxException, JsonParseException, JsonMappingException, IOException, ParseException {
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取调度任务列表开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		QueryFilter<SchedulerTask> filter = new QueryFilter<SchedulerTask>(SchedulerTask.class);
		filter.addFilterFromRequest(request);
		QueryResult<SchedulerTask> result = schedulerTaskService.anyQuery(filter);
		if (null == result || null == result.getResultList() || result.getResultList().size() < 0) {
			log.info("获取调度任务列表失败", user.getLoginId(), user.getUsername(),
					getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取调度任务列表失败"), HttpStatus.OK);
		}
		log.info("获取调度任务列表成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取列表成功", result.getResultList()), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据调度任务唯一ID值获取调度任务
	 * </p>
	 * 
	 * @param id 调度任务唯一ID值
	 * @return ResponseEntity<SchedulerTask>
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@GetMapping("/schedulerTask/get/{id}")
	@Parameter(name = "id", description = "对象唯一Id", required = false)
	@Operation(summary ="获取单个调度任务，若根据调度任务唯一Id获取到了多个对象则发生异常")
	public ResponseEntity<ResultMsg> get(
			@PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个调度任务失败，未给定调度任务的唯一标识"), HttpStatus.OK);
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取调度任务开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		SchedulerTask schedulerTask = schedulerTaskService.get(id);
		/*
		 * <p> ofNullable执行逻辑：如果对象为空，则执行orElse，否则执行.map... return
		 * Optional.ofNullable(sysRole).map(result -> new ResponseEntity<>(result,
		 * HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
		 */
		if (null == schedulerTask) {
			log.info("获取调度任务失败", user.getLoginId(), user.getUsername(),
					getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个调度任务失败，给定的调度任务可能被删除"), HttpStatus.OK);
		}
		log.info("获取调度任务成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取成功", schedulerTask), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据调度任务唯一ID值删除单个调度任务
	 * </p>
	 * 
	 * @param id 调度任务唯一ID值
	 * @return ResponseEntity,json格式
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@GetMapping("/schedulerTask/delete/{id}")
	@Parameter(name = "id", description = "调度任务唯一Id", required = false)
	@Operation(summary ="删除单个调度任务")

	public ResponseEntity<ResultMsg> delete(
		@PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "删除单个调度任务失败，未给定调度任务的唯一标识"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("删除单条调度任务开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		schedulerTaskService.remove(id);
		log.info("删除单条调度任务成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "删除成功"), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据调度任务唯一ID值集合，批量删除调度任务
	 * </p>
	 * 
	 * @param ids 调度任务唯一ID值集合
	 * @return ResponseEntity<ResultMsg>,返回结果中有删除的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@PostMapping("/schedulerTask/deleteBatch")
	@Parameter(name = "ids", description = "逗号分隔的调度任务Id集合", required = false)
	@Operation(summary = "删除调度任务集合")
	
	public ResponseEntity<ResultMsg> deleteBatch(
		@RequestParam String ids) {
		if (StringUtils.isBlank(ids)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "批量删除调度任务失败，未给定调度任务的唯一标识集合"), HttpStatus.OK);
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("批量删除调度任务开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		long rows = schedulerTaskService.deleteBatch(ids);
		log.info("批量删除调度任务成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "批量删除调度任务成功", rows), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据调度任务唯一ID值集合，批量更新调度任务
	 * </p>
	 * 
	 * @param ids            调度任务唯一ID值集合
	 * @param properityName  调度任务要更新的属性名，不带类名
	 * @param properityValue 调度任务要更新的属性值
	 * @return ResponseEntity<ResultMessage>,返回结果中有更新的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@PostMapping("/schedulerTask/updateBatch")
	@Parameters({@Parameter( name = "properityName", description = "要更新的属性名不带类名，只能是类单个属性名且不能是集合类型", required = false),
			@Parameter(name = "properityValue", description="属性值", required = false),
			@Parameter(name = "ids", description="逗号分隔的企业类型Id集合", required = false)
	})
	@Operation(summary ="更新调度任务集合")
	public ResponseEntity<ResultMsg> updateBatch(
			@RequestParam String properityName,
			@RequestParam String properityValue,
			 @RequestParam String ids) {
		if (StringUtils.isBlank(ids) || StringUtils.isBlank(properityValue) || StringUtils.isBlank(properityName)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "批量更新调度任务失败，未给定调度任务的唯一标识集合或属性名或属性值"),
					HttpStatus.OK);
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("批量更新调度任务开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		long rows = schedulerTaskService.updateBatch(properityName, properityValue, ids);
		log.info("批量更新调度任务成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "批量更新调度任务成功", rows), HttpStatus.OK);
	}
	
	@GetMapping("/schedulerTask/isdisable/{schedulerTaskId}")
	@Parameter(name = "schedulerTaskId", description = "调度任务id", required = false)
	@Operation(summary ="启动或者暂停任务")
	public ResponseEntity<ResultMsg> deviceModelUnique(@PathVariable String schedulerTaskId){
		ResultMsg resultMsg = taskManager.startOrStop(schedulerTaskId);
		return new ResponseEntity<ResultMsg>(resultMsg,HttpStatus.OK);
	}
}
